﻿using System.Windows.Forms;
using System;
using System.Globalization;
using Deppton.Model;
namespace Deppton.Mobile.Views
{
    public partial class NewSurveyForm : DepptonForm
    {
        Random random = new Random(DateTime.Now.Millisecond);

        public NewSurveyForm(IServicesPortfolio servicesPortfolio)
        {
            InitializeComponent();

            this.ServicesPortfolio = servicesPortfolio;

            this.UpdateInformation();
            this.SetNewRandomId();
        }

        public void UpdateInformation()
        {
            var definitions = this.ServicesPortfolio.SurveyDefinitionsStorageService.RetrieveAllSurveyDefinitions();

            this.TemplatesComboBox.DataSource = definitions;
        }

        private IServicesPortfolio ServicesPortfolio
        {
            get;
            set;
        }

        private void SetNewRandomId()
        {
            this.SurveyIdTextBox.Text = this.random.Next(1000, 9999).ToString(CultureInfo.InvariantCulture);
        }

        private void ConfirmMenuItemClick(object sender, System.EventArgs e)
        {
            var surveyId = this.SurveyIdTextBox.Text.Trim();

            if (this.ServicesPortfolio.SurveysStorageService.Retrieve(surveyId) != null)
            {
                MessageBox.Show("Another survey with the same Id already exists.");
                return;
            }

            var surveyDefinition = this.ServicesPortfolio.SurveyDefinitionsStorageService.RetrieveSurveyDefinition(this.TemplatesComboBox.SelectedValue as string);

            var survey = this.CreateSurvey(this.SurveyIdTextBox.Text, this.DescriptionTextBox.Text, surveyDefinition);
            this.ServicesPortfolio.SurveysStorageService.Store(survey);

            this.DialogResult = DialogResult.OK;
        }

        private Survey CreateSurvey(string surveyId, string description, SurveyDefinition surveyDefinition)
        {
            var survey = new Survey();

            survey.Id = surveyId;
            survey.SurveyDefinitionId = surveyDefinition.Id;
            survey.Description = description;
            survey.Status = SurveyStatus.Pending;

            foreach (var question in surveyDefinition.Questions)
            {
                survey.QuestionValues.Add(new System.Collections.Generic.KeyValuePair<string, string>(question.Id, string.Empty));
            }

            return survey;
        }

        private void GoBackMenuItemClick(object sender, System.EventArgs e)
        {
            this.DialogResult = System.Windows.Forms.DialogResult.Cancel;
            this.Close();
        }

        private void NewRandomIdButtonClick(object sender, EventArgs e)
        {
            this.SetNewRandomId();
        }
    }
}

